/*
 * Command.cpp
 *
 *  Created on: 20 sep 2010
 *      Author: Juan
 */

#include "Command.h"

Command::Command(string name) {
	this->name = name;
	arguments = new vector<string>();
	infile = "";
	outfile = "";
	append = false;
}

Command::~Command() {
	delete arguments;
}

string Command::getName() {
	return name;
}

void Command::addArgument( string arg ) {
	arguments->push_back( arg );
}

vector<string>* Command::getArguments() {
	return arguments;
}

void Command::setIORedirectionInput( string in ) {
	infile = in;
}

string Command::getIORedirectionInput() {
	return infile;
}

void Command::setIORedirectionOutput( string out ) {
	outfile = out;
}

string Command::getIORedirectionOutput() {
	return outfile;
}

void Command::setAppend() {
	append = true;
}

bool Command::getAppend() {
	return append;
}

void Command::print()
{
	cerr << "Commando: " << name << endl;
	for (unsigned int i=0; i<arguments->size(); i++) {
		cerr << "\targ: " << arguments->at(i) << endl;
	}
	cerr << endl;
}

void Command::exec(){
	int length = 0;

	for(vector<string>::iterator iter = arguments->begin(); iter != arguments->end(); iter++){
		length += (*iter).length();
	}
	length += name.length();

	char ** argv = new char*[length+1];

	argv[0] = new char[name.length()];
	strcpy(argv[0],name.c_str());
	//argv[0] =  getName().c_str();
	int i = 1;
	for(vector<string>::iterator iter = arguments->begin(); iter != arguments->end(); iter++, i++){
		//cout << *iter << endl;
		//cout << iter->length() << endl;
		argv[i] = new char[(*iter).length()];
		//cout << "hier 1" << endl;

		strcpy(argv[i],(*iter).c_str());
		//cout << "hier 2" << endl;

	}
	argv[i+1] = 0;

	cout << "arg0: "<< argv[0] << endl;
	cout << "arg1: "<< argv[1] << endl;
	cout << "size: "<< arguments->size() << endl;
	execvp(argv[0], argv);
}
